from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import mysql.connector

QQNUMBER = 'QQ账号'
QQPASSWORD = 'QQ密码'

browser = webdriver.Chrome(executable_path="./chromedriver.exe")
wait = WebDriverWait(browser, 10)


def save_mysql(title, sender, reciver, recv_time, text):
    cnx = mysql.connector.connect(user='root',
                                  password='123456',
                                  host='127.0.0.1',
                                  port=3306,
                                  database='mail')
    cursor = cnx.cursor()
    query = '''CREATE TABLE IF NOT EXISTS qzsd(
   id INT(11) AUTO_INCREMENT PRIMARY KEY,
   title VARCHAR(255) NOT NULL,
   sender VARCHAR(255) NOT NULL,
   reciver VARCHAR(255) NOT NULL,
   recv_time VARCHAR(255) NOT NULL,
   text LONGTEXT)'''
    cursor.execute(query)
    sql = "INSERT INTO qzsd (title, sender, reciver,recv_time, text) VALUES (%s, %s, %s,%s, %s)"
    val = (title, sender, reciver, recv_time, text)
    cursor.execute(sql, val)
    cnx.commit()
    cursor.close()
    cnx.close()


def mail_qq_login():
    try:
        browser.get("https://mail.qq.com/")
        browser.switch_to.frame("login_frame")
        qq_nb = wait.until(EC.presence_of_element_located((By.ID, "u")))
        qq_pw = wait.until(EC.presence_of_element_located((By.ID, "p")))
        login_bt = wait.until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "#login_button")))
        qq_nb.send_keys(QQNUMBER)
        qq_pw.send_keys(QQPASSWORD)
        login_bt.click()
    except TimeoutException:
        print("超时错误，重新登录...")
        mail_qq_login()


def process(mail_list, index):
    try:
        print(index)
        title = mail_list[index].find_element_by_class_name('tt')
        tt = title.text
        title.click()
        #.text
        tcolors = browser.find_elements_by_class_name('tcolor')
        sender = tcolors[2].text
        recv_time = tcolors[3].text
        receiver = tcolors[4].text
        texts = browser.find_elements_by_tag_name("p")
        text = ' '.join([v.text for v in texts])
        save_mysql(tt, sender, receiver, recv_time, text)
        browser.back()
        main_frame = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "#mainFrame")))
        browser.switch_to.frame(main_frame)
    except Exception:
        print('Not Nolmal mail')


def main():
    mail_qq_login()
    recv_option = wait.until(
        EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "收件箱")))
    recv_option.click()
    main_frame = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#mainFrame")))
    browser.switch_to.frame(main_frame)
    mail_list = browser.find_elements_by_css_selector('.tf.no')
    num = len(mail_list)
    for i in range(num):
        process(mail_list, i)
        mail_list = browser.find_elements_by_css_selector('.tf.no')


if __name__ == '__main__':
    main()